package me.yobol.greentable.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.yobol.greentable.bean.IngredientBean;
import me.yobol.greentable.exception.IllegalOperationException;
import me.yobol.greentable.service.IngredientService;

/**
 * @author Yobol
 *
 */
public class DeleteIngredientServlet extends HttpServlet {

	private static final long serialVersionUID = -1373999739421063043L;

	public DeleteIngredientServlet() {
		super();
	}
	
	public void init() throws ServletException {
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int igId = (request.getParameter("igId") == null) ? -1
				: Integer.parseInt(request.getParameter("igId"));
		int traderId = (request.getSession().getAttribute("uId") == null) ? -1
				: (Integer) request.getSession().getAttribute("uId");
		
		String rediect = null;
		try {
			if(IngredientService.deleteIngredient(igId, traderId)){
				
				if(traderId > 0) {
					List<IngredientBean> igByTraderId = IngredientService.getIngredientByTraderId(traderId);
					request.getSession().setAttribute("ingredient_list", igByTraderId);
				}
			}
		} catch (IllegalOperationException e) {
			System.out.println(e.toString());
			request.setAttribute("msg", e.toString());
		}

		rediect = "/pages/ingredient/ingredient_list.jsp";
		response.sendRedirect(request.getContextPath() + rediect);
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
